const Koa = require('koa')
const router = require('./routers/router')
const views = require('koa-views')
const static = require('koa-static')
// const logger = require('koa-logger')
const body = require("koa-body")
const { join } = require('path')
const session = require('koa-session')
const compress = require('koa-compress')

// 生成 koa 实例
const app = new Koa()

app.keys = ["我hi是ffw"]

const CONFIG = {
  key: "Sid",
  maxAge: 36e5,
  overwrite: true,
  httpOnly: true,
  signed: true, // 是否带签名
  rolling: true //是否刷新
}

// 注册日志模块
// app.use(logger())

// 注册 koa-compress
app.use(compress({
  threshold: 2048,
  flush: require('zlib').Z_SYNC_FLUSH
}))

// 注册 session
app.use(session(CONFIG, app))

// 配置koa-body 处理post请求
app.use(body())
// 配置静态实例
app.use(static(join(__dirname, 'public')))
// 配置视图模板
app.use(views(join(__dirname, 'views'), {
  extension: 'pug'
}))

// 注册路由信息
app
  .use(router.routes())
  .use(router.allowedMethods())
  .listen(6100, () => {
    console.log('项目启动成功，监听在 6100 端口')
  })

{
  
  const { db } = require('./Schema/connect')
  const encrypt = require('./utils/encrypt')

  const ArticleSchema = require('./Schema/article')
  const Article = db.model("articles", ArticleSchema)

  const UserScema = require('./Schema/user')
  const User = db.model("users", UserScema)

  const CommentSchema = require('./Schema/comment')
  const Comment = db.model("comments", CommentSchema)

  User
    .find({username: "admin"})
    .then(data => {
      if(data.length === 0) {
        new User({
          username: "admin",
          password: encrypt("admin"),
          role: 666,
          commentNum: 0,
          articleNum: 0
        })
        .save()
        .then()
        .catch(err => {
          console.log(err);
          
        })

      } else {
        console.log(`管理员用户名为->admin 密码为->admin`)
      }
    })

}